<?php
/*
  $Id: PayGateZA_PayWebv2.php,v 1.01 2004/01/21

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

// ##################################################################################
// Title                     : PayGate South Africa OSCommerce Payment Module
//                             Uses the PayWebv2 interface
// Version                   : 1.0
// Author                    : PayGate
// Last modification date    : 2004-05-13
// Notes                     : A payment module extenstion for OSCommerce.
//                             You will require a PayGate account to make use of this
//                             module in a live environment.
//                             Visit www.paygate.co.za for more info.
// ##################################################################################
// History:
// 2004-05-13                : First version of this class.
// ##################################################################################


  class paygateza_paywebv2 {
    var $code, $title, $description, $enabled;

// class constructor
    function paygateza_paywebv2() {
      global $order;

      $this->code = 'PayGateZA_PayWebv2';
      $this->title = MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_TITLE;
      $this->description = MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_DESCRIPTION;
      $this->enabled = ((MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS == 'True') ? true : false);

      if ((int)MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ORDER_STATUS_ID > 0) {
        $this->order_status = MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ORDER_STATUS_ID;
      }

      if (is_object($order)) $this->update_status();

//      $this->form_action_url = tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL', false);
      $this->form_action_url = 'https://www.paygate.co.za/paywebv2/process.trans';
    }

    function update_status() {
      global $order;

      if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE > 0) ) {
        $check_flag = false;
        $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }

        if ($check_flag == false) {
          $this->enabled = false;
        }
      }
    }

    function javascript_validation() {
      return false;
    }

    function selection() {
      return array('id' => $this->code,
                   'module' => $this->title);
    }

    function pre_confirmation_check() {
      return false;
    }

    function confirmation() {
      return false;
    }

    function process_button() {
       global $HTTP_POST_VARS, $shipping_cost, $shipping_selected, $shipping_method, $customer_id , $order;
/*****************************/
/* Data required by PayGate: */
/*  - PayGate ID             */
/*  - Reference Number       */
/*  - Amount                 */
/*  - Currency               */
/*  - Return URL             */
/*  - Transaction Date       */
/*  - Checksum               */
/*****************************/
	  $pgPayGateID = MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_PAYGATEID;
	  $pgReference = 'CID:' . $customer_id . ' ** ' . date("Y-m-d H:i");
	  $pgAmount = (string)((int)($order->info['total']*100));
	  $pgCurrency = "ZAR";
	  $pgReturnURL = tep_href_link(FILENAME_CHECKOUT_PROCESS, 'shipping_selected=' . urlencode($shipping_selected) . '&shipping_cost=' . urlencode($shipping_cost) . '&shipping_method=' . urlencode($shipping_method), 'SSL');
	  $pgTransactionDate = gmstrftime("%Y-%m-%d %H:%M");

/***************************************************************/
/* Concate the fields above to form the source of the checksum */
/* Then append the encryption key                              */
/***************************************************************/
	  $checksumSource = $pgPayGateID."|".$pgReference."|".$pgAmount."|".$pgCurrency."|".html_entity_decode($pgReturnURL)."|".$pgTransactionDate."|".MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY;
	  $pgChecksum = md5($checksumSource);

   // The process_button_string contains the form that is sent to PayGate.
      $process_button_string = tep_draw_hidden_field('PAYGATE_ID', $pgPayGateID) .
                               tep_draw_hidden_field('REFERENCE', $pgReference) .
                               tep_draw_hidden_field('AMOUNT', $pgAmount) .
							   tep_draw_hidden_field('CURRENCY', $pgCurrency) .
                               tep_draw_hidden_field('RETURN_URL', $pgReturnURL) .
							   tep_draw_hidden_field('TRANSACTION_DATE', $pgTransactionDate) .
                               tep_draw_hidden_field('CHECKSUM', $pgChecksum);
      return $process_button_string;
    }

    function before_process() {
      global $HTTP_POST_VARS, $order;

/******************************/
/* Data returned by PayGate:  */
/*  - PayGate ID              */
/*  - Reference Number        */
/*  - Transaction Status      */
/*  - Result Code             */
/*  - Authorisation Code      */
/*  - Amount                  */
/*  - Result Code Description */
/*  - Transaction ID          */
/*  - Checksum                */
/******************************/
	  $pgPayGateID = $HTTP_POST_VARS['PAYGATE_ID'];
	  $pgReference = $HTTP_POST_VARS['REFERENCE'];
	  $pgTransactionStatus = $HTTP_POST_VARS['TRANSACTION_STATUS'];
	  $pgResultCode = $HTTP_POST_VARS['RESULT_CODE'];
	  $pgAuthCode = $HTTP_POST_VARS['AUTH_CODE'];
	  $pgAmount = $HTTP_POST_VARS['AMOUNT'];
	  $pgResultDesc = $HTTP_POST_VARS['RESULT_DESC'];
	  $pgTransactionID = $HTTP_POST_VARS['TRANSACTION_ID'];
	  $pgChecksum = $HTTP_POST_VARS['CHECKSUM'];
   
/**************************************************************/
/* Concate the fields returned (except the checksum) to form  */
/* the source of the checksum. Then append the encryption key */
/**************************************************************/
	  $checksumSource = $pgPayGateID."|".$pgReference."|".$pgTransactionStatus."|".$pgResultCode."|".$pgAuthCode."|".$pgAmount."|".$pgResultDesc."|".$pgTransactionID."|".MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY;
	  $myChecksum = md5($checksumSource);

/*****************************************************/
/* Then compare PayGate IDs, amounts & order numbers */
/*****************************************************/
      if ($myChecksum != $pgChecksum) {
          if (MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG == "True") {
// In debug mode so show which bit of data is causing the error.
              tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("No match on Checksum - before:".$pgChecksum." - after:".$myChecksum), 'SSL', true, false));
          } else {
              tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_DATA_ERROR), 'SSL', true, false));
          }
      }
      
/************************************************************/
/* Now check the transaction status; we're intrested in a 1 */
/************************************************************/
      if ($pgTransactionStatus == "1") {
// If transaction is successful; then auth code should be non-zero and resultcode should be 990017.
          if (($pgResultCode != "990017") || ($pgAuthCode == "")) {
              if (MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG == "True") {
                  if ($pgResultCode != "990017") {
                      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Expecting a ResultCode of 990017; is: ".$pgResultCode), 'SSL', true, false));
                  } elseif ($pgAuthCode == "") {
                      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Expecting an AuthCode but it is blank"), 'SSL', true, false));
                  }
              } else {
                  tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_DATA_ERROR), 'SSL', true, false));
              }
          }
          
// Transaction is approved and authcode and result code look right.
// Checksums, amount and paygateid also match so continue to order confirmation.
// ie. do nothing; OSCommerce takes care of the rest.


      } elseif ($pgTransactionStatus == "0") {
// Transaction status of 0 means problem with PayGate server.
          if ($pgResultCode == "990024" || $pgResultCode == "990028") {
              if (MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG == "True") {
                  tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Transaction not successful; ResultCode: ".$pgResultCode."; Description: ".$pgResultDesc), 'SSL', true, false));
              } else {
                  tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_DECLINED_MESSAGE.$pgResultDesc), 'SSL', true, false));
	 		  }
		  }	else {
              tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_ERROR_MESSAGE), 'SSL', true, false));
		  }
      } else {
// Transaction is declined so print error message
          if (MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG == "True") {
              tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Transaction not successful; ResultCode: ".$pgResultCode."; Description: ".$pgResultDesc), 'SSL', true, false));
          } else {
              tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_DECLINED_MESSAGE.$pgResultDesc), 'SSL', true, false));
          }

      }
    }

    function after_process() {
      return false;
    }

    function get_error() {
      global $HTTP_GET_VARS;

      $error = array('title' => MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_TEXT_ERROR,
                     'error' => stripslashes(urldecode($HTTP_GET_VARS['error'])));

      return $error;
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }
    
    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable PayGate PayWebv2 Module', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS', 'True', 'Do you want to accept PayGate payments?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PayGate ID', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_PAYGATEID', '10011013800', 'Your PayGate ID', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encryption Key', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY', 'secret', 'Your Encryption Key; this must be identical to the Encryption Key on the BackOffice', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Debug Mode', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG', 'False', 'Allows greater detailed error messages for testing purposes.', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    }
// Hashed out and replaced with code above, default order status functions
//    function install() {
//      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable PayGate PayWebv2 Module', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS', 'True', 'Do you want to accept PayGate payments?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
//      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PayGate ID', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_PAYGATEID', '10011013800', 'Your PayGate ID', '6', '0', now())");
//      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Encryption Key', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY', 'secret', 'Your Encryption Key; this must be identical to the Encryption Key on the BackOffice', '6', '0', now())");
//      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
//      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Debug Mode', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG', 'False', 'Allows greater detailed error messages for testing purposes.', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
//    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }
// Hashed out and replaced with code above, default order status functions
//    function keys() {
//      return array('MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_PAYGATEID', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG');
//	 }
    function keys() {
	return array('MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_STATUS', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_PAYGATEID', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ENCRYPTIONKEY', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ZONE', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_DEBUG', 'MODULE_PAYMENT_PAYGATEZA_PAYWEBv2_ORDER_STATUS_ID');
          }
  }
?>
